﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using VRA.Dto;
using VRA.BusinessLayer;

namespace ViewRidgeAssistant
{
    /// <summary>
    /// Логика взаимодействия для AddTransactionWindow.xaml
    /// </summary>
    public partial class AddTransactionWindow : Window
    {
        private static readonly IList<CustomerDto> Customers = ProcessFactory.GetCustomerProcess().GetList();
        private static readonly IList<WorkDto> Works = ProcessFactory.GetWorkProcess().GetList();
        private int id;

        public void Load(TransactionDto Trans)
        {
            this.id = Trans.TransactionID;
            this.loadWork(Trans.WorkID);

            if (Trans.AcquisitionPrice.HasValue) this.tbAcquisitionPrice.Text = Trans.AcquisitionPrice.ToString();
            if (Trans.AskingPrice.HasValue) this.tbAskingPrice.Text = Trans.AskingPrice.ToString();
            if (Trans.SalesPrice.HasValue) this.tbSalesPrice.Text = Trans.SalesPrice.ToString();
            if (Trans.PurchaseDate.HasValue) this.dpPurchase.Text = Trans.PurchaseDate.ToString();
            if (Trans.DateAcquired.HasValue) this.dpAcuired.Text = Trans.DateAcquired.ToString();
            if (Trans.CustomerID.HasValue) loadCustomer(Trans.CustomerID);
        
        }


       
// проверить
        private void loadCustomer(int? id)
        {
            foreach (CustomerDto customer in Customers)
            {
                if (customer.Id == id)
                { this.cbCustomer.SelectedItem = customer; return; }
                    
            }
        }

        private void loadWork(int? id)
        {
            foreach (WorkDto work in Works)
            {
                if (work.Id == id)
                { this.cbWork.SelectedItem = work; this.tbCopy.Text = work.Copy; return; }
            }
            
        }

        public AddTransactionWindow()
        {
            InitializeComponent();
            this.cbCustomer.ItemsSource = Customers;
            this.cbWork.ItemsSource = Works;
            this.dpAcuired.IsTodayHighlighted=true;       
            
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            TransactionDto transaction = new TransactionDto();
            WorkDto SelectedWork = (WorkDto)this.cbWork.SelectedItem;

            transaction.WorkID = SelectedWork.Id;
            if (!string.IsNullOrEmpty(tbAcquisitionPrice.Text))
            {
                try
                {
                    transaction.AcquisitionPrice = Convert.ToDecimal(tbAcquisitionPrice.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Введите корректную цену приобретения"); return;
                }
            }
            if (!string.IsNullOrEmpty(tbAskingPrice.Text))
            {
                try
                {
                    transaction.AskingPrice = Convert.ToDecimal(tbAskingPrice.Text);
                }
                catch (Exception ex)
                {
                     MessageBox.Show("Введите корректную запрашиваемую цену"); return;
                }
                
            }

            if (!string.IsNullOrEmpty(this.dpAcuired.Text))
            {
                transaction.DateAcquired = Convert.ToDateTime(this.dpAcuired.Text);
            }

            if (!string.IsNullOrEmpty(this.dpPurchase.Text))
            {
                if (Convert.ToDateTime(dpPurchase.Text) > Convert.ToDateTime(dpAcuired.Text))
                    transaction.PurchaseDate = Convert.ToDateTime(this.dpPurchase.Text);
                else
                {
                    MessageBox.Show("Нельзя продать работу раньше, чем её купила галерея! Проверьте правильность ввода данных.");
                    return;
                }
            }
            if (!string.IsNullOrEmpty(cbCustomer.Text))
            {
                CustomerDto SelectedCustomer = (CustomerDto)this.cbCustomer.SelectedItem;
                transaction.CustomerID = SelectedCustomer.Id;
            }


            if (!string.IsNullOrEmpty (tbSalesPrice.Text))
            {

                try
                {
                 if(Convert.ToDecimal(tbSalesPrice.Text) >= 30000 && Convert.ToDecimal(tbSalesPrice.Text) <= 1500000)
                    transaction.SalesPrice = Convert.ToDecimal(tbSalesPrice.Text);
                    else
                    {
                     MessageBox.Show("Продажа может проходить только в пределах от 30 тыс. у.е. до 1,5 млн. у.е.");
                        return;
                    }
                }
                catch (System.Exception ex)
                {
                	MessageBox.Show("Невеный формат данных при операции с ценой продажи");return;
                }
                
            }
            ITransactionProcess transProcess = ProcessFactory.GetTransactionProcess();

            if (id == 0)
                transProcess.Add(transaction);
            else
            {
                transaction.TransactionID = id;
                transProcess.Update(transaction);
            }
            this.Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        // заполнение комбика с описаниями копий картины
        private void cbWork_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
          
            WorkDto select = (WorkDto) this.cbWork.SelectedItem;
            this.tbCopy.Text = select.Copy.ToString();

          
        }
    }
}
